#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <strings.h>
#include <ctype.h>
#include <pthread.h>

int clnt_cnt = 0;
int clnt_socks[256];
pthread_mutex_t mutex;

void *handle_clnt(void *arg);
void send_msg(char *msg, int len);

int main(int argc, char *argv[]){

    // 参数检查  
    if (argc < 2){
        fprintf(stderr, "Usage argc ... \n");
        exit(-1);
    }

    // 监听文件描述符
    int lfd = socket(PF_INET, SOCK_STREAM, 0);
    if(lfd < 0){
        fprintf(stderr, "socket error \n");
        exit(-1);
    }  

    // 绑定端口号
    struct sockaddr_in ser_addr;
    bzero(&ser_addr, sizeof(ser_addr));
    ser_addr.sin_family = AF_INET;
    ser_addr.sin_port = htons(atoi(argv[1]));
    ser_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    if(bind(lfd, (struct sockaddr *)&ser_addr, sizeof(ser_addr)) < 0){
        fprintf(stderr, "bind error \n");
        exit(-1);
    }

    // 监听
    if (listen(lfd, 128) < 0){
        fprintf(stderr, "listen error \n");
        exit(-1);
    }
    
    // 初始化互斥变量
    pthread_mutex_init(&mutex, NULL);
    // 线程
    pthread_t tid;

    // 数据传送
    struct sockaddr_in cli_addr;
    socklen_t cli_len = sizeof(cli_addr);
    bzero(&cli_addr, cli_len);

    while (1){
        int cfd = accept(lfd, (struct sockaddr *)&cli_addr, &cli_len);
        if(cfd < 0){
            fprintf(stderr, "accept error \n");
            exit(-1);
        }  

        pthread_mutex_lock(&mutex);
        clnt_socks[clnt_cnt++] = cfd;
        pthread_mutex_unlock(&mutex);

        pthread_create(&tid, NULL, handle_clnt, (void *)&cfd);
        pthread_detach(tid); // 线程分离
        printf("Connected client is: ip=[%s] port=[%d]\n", inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port));
    }
    
    close(lfd);
    return 0;
}

void *handle_clnt(void *arg){
    int cfd = *((int *)arg);
    int str_len = 0;
    char msg[1024];
    while ((str_len = read(cfd, msg, sizeof(msg))) != 0){
        send_msg(msg, str_len);
    }

    pthread_mutex_lock(&mutex);
    for (int i = 0; i < clnt_cnt; i++){
        if(cfd == clnt_socks[i]){
            while (i < clnt_cnt - 1){
                clnt_socks[i] = clnt_socks[i + 1]; // 向前移
                i++;
            }
            break;
        }  
    }
    clnt_cnt--;
    pthread_mutex_unlock(&mutex);
    close(cfd);
    return NULL;
}

void send_msg(char *msg, int len){
    pthread_mutex_lock(&mutex);
    for (size_t i = 0; i < clnt_cnt; i++){ // 给所有的都发一次
        write(clnt_socks[i], msg, len);
    }
    pthread_mutex_unlock(&mutex);   
}